package com.mxx.common.utils;

import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @Author itzgyw
 * @Date 2020-01-30
 * @Time 23:03
 * @Description:
 */
public class CollectionUtil {

    public static final Supplier<TreeSet<?>> TreeSet = () -> new TreeSet<>();
    public static final Supplier<HashSet<?>> HashSet = () -> new HashSet<>();
    public static final Supplier<ArrayList<?>> ArrayList = () -> new ArrayList<>();
    public static final Supplier<LinkedList<?>> LinkedList = () -> new LinkedList<>();

    public static <T> T first(Collection<T> collection, T defaultVal) {
        if (collection == null || collection.isEmpty()) {
            return defaultVal;
        }
        Iterator<T> iterator = collection.iterator();
        iterator.hasNext();
        return iterator.next();
    }

    public static <T> T first(Collection<T> collection) {
        if (collection == null || collection.isEmpty()) {
            return null;
        }
        Iterator<T> iterator = collection.iterator();
        iterator.hasNext();
        return iterator.next();
    }

    public static <T> boolean notExists(T[] tArray, T val) {
        return !CollectionUtil.exists(tArray, val);
    }

    public static <T> boolean exists(T[] tArray, T val) {
        for (int index = 0; index < tArray.length; index++) {
            if (val.equals(tArray[index])) {
                return true;
            }
        }
        return false;
    }

    public static <T> List<T> toList(T... tArray) {
        List<T> tList = new ArrayList<>(tArray.length);
        return CollectionUtil.toList(tList, tArray);
    }

    public static <T> List<T> toList(List<T> list, T... tArray) {
        for (int i = 0; i < tArray.length; i++) {
            list.add(tArray[i]);
        }
        return list;
    }

    public static <T> Set<T> toSet(T... tArray) {
        Set<T> tSet = new TreeSet<>();
        return CollectionUtil.toSet(tSet, tArray);
    }

    public static <T> Set<T> toSet(Comparator comparator, T... tArray) {
        Set<T> tSet = new TreeSet<>(comparator);
        return CollectionUtil.toSet(tSet, tArray);
    }

    public static <T> Set<T> toSet(Set<T> set, T... tArray) {
        for (int i = 0; i < tArray.length; i++) {
            set.add(tArray[i]);
        }
        return set;
    }
}
